<template>
    <div class="supplier-detail">
        <div class="header">
            <div class="nav-bar">
                <p class="font16">供应商详情</p>
                <router-link to="/supplier">
                    <el-button class="back-btn">返回</el-button>
                </router-link>
            </div>
        </div>
        
        <div class="detail-content" v-loading="loading">
            <el-row :gutter="20">
                <el-col :span="16">
                    <div class="detail-card">
                        <h3 class="card-title">基本信息</h3>
                        
                        <el-row class="info-item">
                            <el-col :span="4" class="label">公司名称：</el-col>
                            <el-col :span="20" class="value">{{supplier.name}}</el-col>
                        </el-row>
                        
                        <el-row class="info-item">
                            <el-col :span="4" class="label">简称：</el-col>
                            <el-col :span="20" class="value">{{supplier.code}}</el-col>
                        </el-row>
                        
                        <el-row class="info-item">
                            <el-col :span="4" class="label">主营业务：</el-col>
                            <el-col :span="20" class="value">{{supplier.business_scope || '-'}}</el-col>
                        </el-row>
                        
                        <el-row class="info-item">
                            <el-col :span="4" class="label">联系方式：</el-col>
                            <el-col :span="20" class="value">{{supplier.phone || '-'}}</el-col>
                        </el-row>
                        
                        <el-row class="info-item">
                            <el-col :span="4" class="label">总部地址：</el-col>
                            <el-col :span="20" class="value">{{supplier.address || '-'}}</el-col>
                        </el-row>
                        
                        <el-row class="info-item">
                            <el-col :span="4" class="label">成立时间：</el-col>
                            <el-col :span="20" class="value">{{formatDate(supplier.found_time) || '-'}}</el-col>
                        </el-row>
                        
                        <el-row class="info-item">
                            <el-col :span="4" class="label">状态：</el-col>
                            <el-col :span="20" class="value">
                                <el-tag type="success" v-if="supplier.status === 'active'">正常</el-tag>
                                <el-tag type="danger" v-else-if="supplier.status === 'inactive'">已禁用</el-tag>
                                <span v-else>{{supplier.status || '-'}}</span>
                            </el-col>
                        </el-row>
                    </div>
                    
                    <div class="detail-card">
                        <h3 class="card-title">供应产品</h3>
                        <el-table :data="productList" style="width: 100%">
                            <el-table-column prop="name" label="产品名称"></el-table-column>
                            <el-table-column prop="category" label="类别"></el-table-column>
                            <el-table-column prop="shelfLife" label="保质期">
                                <template scope="scope">
                                    {{scope.row.shelfLife}} 天
                                </template>
                            </el-table-column>
                            <el-table-column prop="price" label="价格">
                                <template scope="scope">
                                    ¥ {{scope.row.price}}
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-col>
                
                <el-col :span="8">
                    <div class="detail-card">
                        <h3 class="card-title">资质证书</h3>
                        <div class="certificate-list">
                            <div class="certificate-item" v-for="(cert, index) in certificates" :key="index">
                                <img :src="cert.url" class="cert-img" @click="previewImage(cert.url)">
                                <p class="cert-name">{{cert.name}}</p>
                            </div>
                            <div class="empty-tip" v-if="certificates.length === 0">
                                暂无资质证书
                            </div>
                        </div>
                    </div>
                    
                    <div class="detail-card">
                        <h3 class="card-title">供应商评价</h3>
                        <div class="rating">
                            <div class="rating-score">
                                <span class="score">{{supplier.rating || 4.8}}</span>
                                <span class="max-score">/5.0</span>
                            </div>
                            <div class="rating-stars">
                                <el-rate
                                    v-model="supplier.rating"
                                    disabled
                                    show-score
                                    text-color="#ff9900">
                                </el-rate>
                            </div>
                        </div>
                        
                        <div class="rating-items">
                            <div class="rating-item">
                                <span class="item-label">产品质量</span>
                                <el-progress :percentage="supplier.qualityRating || 95" :stroke-width="10"></el-progress>
                            </div>
                            <div class="rating-item">
                                <span class="item-label">交付及时性</span>
                                <el-progress :percentage="supplier.deliveryRating || 92" :stroke-width="10"></el-progress>
                            </div>
                            <div class="rating-item">
                                <span class="item-label">服务态度</span>
                                <el-progress :percentage="supplier.serviceRating || 97" :stroke-width="10"></el-progress>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>
            
            <div class="action-bar">
                <router-link :to="{path: '/supplier/edit', query: {id: supplierId}}">
                    <el-button type="primary">编辑</el-button>
                </router-link>
                <el-button @click="handleProducts">管理产品</el-button>
                <el-button type="danger" @click="handleDelete">删除供应商</el-button>
            </div>
        </div>
        
        <el-dialog :visible.sync="previewVisible" size="tiny">
            <img width="100%" :src="previewImageUrl" alt="">
        </el-dialog>
    </div>
</template>

<script>
    import axios from 'axios';
    
    export default {
        data() {
            return {
                supplierId: '',
                loading: false,
                supplier: {
                    name: '',
                    code: '',
                    business_scope: '',
                    phone: '',
                    address: '',
                    found_time: '',
                    rating: 4.8,
                    qualityRating: 95,
                    deliveryRating: 92,
                    serviceRating: 97
                },
                productList: [],
                certificates: [],
                previewVisible: false,
                previewImageUrl: ''
            }
        },
        
        created() {
            this.supplierId = this.$route.query.id;
            if (this.supplierId) {
                this.getSupplierDetail();
                this.getSupplierProducts();
            }
        },
        
        methods: {
            getSupplierDetail() {
                this.loading = true;
                
                // 实际API调用
                axios.get(`/api/suppliers/${this.supplierId}`)
                .then(response => {
                    if (response.data.status === 'success') {
                        this.supplier = response.data.supplier;
                        // 设置默认评分
                        if (!this.supplier.rating) {
                            this.supplier.rating = 4.8;
                            this.supplier.qualityRating = 95;
                            this.supplier.deliveryRating = 92;
                            this.supplier.serviceRating = 97;
                        }
                        this.certificates = response.data.certificates || [];
                    } else {
                        this.$message.error(response.data.message || '获取供应商数据失败');
                    }
                    this.loading = false;
                })
                .catch(err => {
                    console.log(err);
                    this.$message.error('获取供应商数据失败');
                    this.loading = false;
                });
            },
            
            getSupplierProducts() {
                // API调用获取供应商相关产品
                axios.get(`/api/products`, {
                    params: {
                        supplier_id: this.supplierId
                    }
                })
                .then(response => {
                    if (response.data.status === 'success') {
                        this.productList = response.data.items || [];
                    } else {
                        console.log('获取产品列表失败:', response.data.message);
                        this.productList = [];
                    }
                })
                .catch(err => {
                    console.log('获取产品列表错误:', err);
                    this.productList = [];
                });
            },
            
            handleDelete() {
                this.$confirm('确认删除该供应商？此操作不可恢复', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete(`/api/suppliers/${this.supplierId}`)
                    .then(response => {
                        if (response.data.status === 'success') {
                            this.$message.success('供应商删除成功');
                            this.$router.push('/supplier');
                        } else {
                            this.$message.error(response.data.message || '删除失败');
                        }
                    })
                    .catch(err => {
                        if (err.response && err.response.data && err.response.data.message) {
                            this.$message.error(err.response.data.message);
                        } else {
                            console.log(err);
                            this.$message.error('删除供应商失败');
                        }
                    });
                }).catch(() => {
                    // 取消删除
                });
            },
            
            handleProducts() {
                this.$router.push({
                    path: '/product',
                    query: { supplier_id: this.supplierId }
                });
            },
            
            previewImage(url) {
                this.previewImageUrl = url;
                this.previewVisible = true;
            },
            
            formatDate(date) {
                if (!date) return '-';
                
                try {
                    // 如果是日期对象，直接格式化
                    if (date instanceof Date) {
                        return date.toLocaleDateString();
                    }
                    
                    // 如果是字符串，尝试转换
                    const dateObj = new Date(date);
                    if (isNaN(dateObj.getTime())) {
                        return date; // 如果无法转换，返回原始值
                    }
                    
                    // 格式化为 YYYY-MM-DD
                    return dateObj.toISOString().split('T')[0];
                } catch (e) {
                    console.error('日期格式化错误:', e);
                    return date; // 出错时返回原始值
                }
            }
        }
    }
</script>

<style scoped>
    .supplier-detail {
        padding: 20px;
        background-color: #fff;
    }
    
    .header {
        padding: 15px;
        padding-top: 10px;
        margin-bottom: 20px;
    }
    
    .nav-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    
    .back-btn {
        width: 100px;
        border-radius: 20px;
    }
    
    .detail-card {
        margin-bottom: 20px;
        padding: 20px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
    
    .card-title {
        margin-top: 0;
        margin-bottom: 20px;
        padding-bottom: 10px;
        font-size: 16px;
        font-weight: bold;
        border-bottom: 1px solid #ebeef5;
    }
    
    .info-item {
        margin-bottom: 15px;
    }
    
    .label {
        color: #909399;
        text-align: right;
        padding-right: 10px;
    }
    
    .value {
        color: #333;
    }
    
    .certificate-list {
        display: flex;
        flex-wrap: wrap;
    }
    
    .certificate-item {
        width: 120px;
        margin-right: 10px;
        margin-bottom: 10px;
        text-align: center;
    }
    
    .cert-img {
        width: 100%;
        height: 100px;
        object-fit: cover;
        border-radius: 4px;
        cursor: pointer;
        border: 1px solid #ebeef5;
    }
    
    .cert-name {
        margin-top: 5px;
        font-size: 12px;
        color: #606266;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
    }
    
    .empty-tip {
        width: 100%;
        padding: 30px 0;
        text-align: center;
        color: #909399;
    }
    
    .rating {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
    }
    
    .rating-score {
        margin-right: 20px;
    }
    
    .score {
        font-size: 28px;
        font-weight: bold;
        color: #ff9900;
    }
    
    .max-score {
        font-size: 14px;
        color: #909399;
    }
    
    .rating-item {
        margin-bottom: 15px;
    }
    
    .item-label {
        display: block;
        margin-bottom: 5px;
        color: #606266;
    }
    
    .action-bar {
        margin-top: 20px;
        text-align: center;
    }
</style> 